﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;

namespace mojoPortal.Web.RS.AppCode.Lib
{
    public class SQLHelper
    {
        public static void AddParamToSQLCmd(SqlCommand sqlCmd,string paramId,SqlDbType sqlType,int paramSize,ParameterDirection paramDirection,object paramvalue)
        {

            if (sqlCmd == null)
                throw (new ArgumentNullException("sqlCmd"));
            if (paramId == string.Empty)
                throw (new ArgumentOutOfRangeException("paramId"));

            SqlParameter newSqlParam = new SqlParameter();
            newSqlParam.ParameterName = paramId;
            newSqlParam.SqlDbType = sqlType;
            newSqlParam.Direction = paramDirection;

            if (paramSize > 0)
                newSqlParam.Size = paramSize;

            if (paramvalue != null)
                newSqlParam.Value = paramvalue;

            sqlCmd.Parameters.Add(newSqlParam);
        }

        public static void ExecuteScalarCmd_ReadyServiceMain(SqlCommand sqlCmd)
        {
            string rsConnectionStringMain = "ReadyServiceConnectionStringMain";
            if (sqlCmd == null)
                throw (new ArgumentNullException("sqlCmd"));

            using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings[rsConnectionStringMain].ToString()))
            {
                sqlCmd.Connection = cn;
                cn.Open();
                sqlCmd.ExecuteScalar();
                cn.Close();
            }
        }

        public static void ExecuteScalarCmd(SqlCommand sqlCmd)
        {
            string companyConnectionString = RSCommonFunctions.GetRSCompanyConnectionString();
            if (companyConnectionString.Length == 0)
                throw (new ArgumentOutOfRangeException("ConnectionString"));

            if (sqlCmd == null)
                throw (new ArgumentNullException("sqlCmd"));

            using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings[companyConnectionString].ToString()))
            {
                sqlCmd.Connection = cn;
                cn.Open();
                sqlCmd.ExecuteScalar();
                cn.Close();
            }
        }

        public static void SetCommandType(SqlCommand sqlCmd, CommandType cmdType, string cmdText)
        {
            sqlCmd.CommandType = cmdType;
            sqlCmd.CommandText = cmdText;
        }

    }
}